/*
 * HTML5 Web application framework
 *
 * REQUIRES: jQuery, jTemplates
 *
 * (c) Andreas Kasch
 */

var H5 = new function(){
	
	/*
	 * Method Aliases
	 */
	this.t = function(key){
		return H5.Locale.t(key);
	};
	this.loadPage = function(identifier, args){
		return H5.PageLoader.load(identifier, args);
	};
	this.includeScript = function(filename, callback){
		return H5.ScriptLoader.include(filename, callback);
	};

	/*
	 * Global variables
	 */
	this.Pages = {};
	this.Strings = {};
	var random = new Date().getTime();
	
	/*
	 * Methods
	 */
	this.init = function(){
		/*
		 * The following code snipplet requires jQuery.
		 */
		{
			$(document).on("click", ".h5-page-link", function(){
				var pageId = $(this).attr("href").replace("#","");
				H5.PageLoader.load(pageId);
				return false;
			});
			
			$(document).on("click", ".h5-external-link", function(){
				var pageUrl = $(this).attr("href");
				var win=window.open(pageUrl, '_blank');
				win.focus();
				return false;
			});
			
			$(document).on("click", ".h5-toggle-link", function(){
				var target = $(this).attr("href").replace("#","");
				if($(this).hasClass("slide")){
					$("." + target + ", #" + target).slideToggle();
				} else if($(this).hasClass("fade")){
					$("." + target + ", #" + target).fadeToggle();
				} else{
					$("." + target + ", #" + target).toggle();
				}
				
				return false;
			});
			
			$(document).on("click", ".h5-back-link", function(){
				H5.PageLoader.back();
				return false;
			});
			
			if(H5.isMobile()){
				$("body").addClass("mobile");
			} else {
				$("body").addClass("desktop");
			}	
			
		}
				
		document.addEventListener("backbutton", H5.PageLoader.back, false);
	};
	
	this.getRandom = function(){
		/* Method to get a random number that is recalculated with every app start. Used to force scripts/styles to be reloaded. */
		return random;
	};
	
	this.getUrlParam = function(id){
		var vars = {};
		window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
			vars[key] = value;
		});
		if(id){
			if(vars[id]){
				return vars[id];
			} else {
				return null;
			}
		} else {
			return vars;
		}
	};
	
	this.preloadImages = function(sources, onSuccess, onError) {
		var images = {};
		var loadedImages = 0;
		var numImages = 0;
		var error = false;
		for(var src in sources) {
			numImages++;
		}
		if(numImages == 0) onSuccess({});
		for(var src in sources) {
			images[src] = new Image();
			images[src].onload = function() {
				if (this.width + this.height <= 0) {
					this.onerror();
					return;
				}
				if(++loadedImages >= numImages) {
					onSuccess(images);
				}
			};
			images[src].onerror = function() {
				onError(this.src);
				error = true;
				return;
			}
			images[src].src = sources[src];
			if(error) return;
		}
	};
	
	this.redirectToHTTPS = function(){
		if (window.location.protocol == "http:"){
			window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);
		}
	};
	
	this.isMobile = function(){
		var check = false;
		(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
		return check;
	}
	
	/*
	 * Classes
	 */
	this.ScriptLoader = new function(){
		var included = [];
		this.include = function(filename, callback){
			for(var i = 0; i < included.length; i++){
				if(included[i] == filename){
					callback();
					return;
				}
			}
			included.push(filename);
			var head = document.getElementsByTagName('head').item(0);
			script = document.createElement('script');
			script.src = filename;
			script.type = 'text/javascript';
			head.appendChild(script);
			if(callback){
				script.addEventListener("load",callback,false);
			}
			return this;
		};
	};
	
	this.PageLoader = new function(){
		var history = [];
		var currentPage = null;
		var pagePath = "page/";
		this.setPath = function(path){
			pagePath = path;
		};
		this.load = function(identifier, args){
			H5.ScriptLoader.include(pagePath + identifier + ".js?v=" + random, function(){
				var page = forName(identifier);
				
				if(typeof page !== "undefined" && page.load){
					
					page.preload(args, function(tplObject, includes){
						if(currentPage != null && currentPage.unload){
							currentPage.unload();
						}
					
						/*
						 * The following code snipplet requires jQuery and jTemplates.
						 */
						{
							tplObject.onload = function(){
								window.setTimeout(page.load,1);
							}; // binds the load method of the new page to the onload argument of the template object
							$("#h5-page-content").setTemplateURL(pagePath + identifier + ".html?v=" + random, includes, {runnable_functions: true, filter_data: false}).processTemplate(tplObject);
							$(".h5-page-link").each(function(){
								$(this).removeClass("active");
								if($(this).attr("href").replace("#","") == identifier) $(this).addClass("active");
							});
						}
						
						if(page.options){
							if(page.options.clearHistory) history = [];
							if(page.options.addToHistory) history.push({
									id: identifier,
									args: args,
								});
						}
						
						
						currentPage = page;
					});
					
				}
				
			});
		};
		this.back = function(){
			if(currentPage && currentPage.options && currentPage.options.addToHistory && history.length > 0) history.pop();
			if(history.length > 0){
				var newPage = history.pop();
				H5.PageLoader.load(newPage.id, newPage.args);
			}
		};	
		var forName = function(identifier){
			return new Function('return H5.Pages.' + identifier)();
		};
	};
	
	this.Locale = new function(){
		this.DEFAULT_LANGUAGE = "en";
		var lang = this.DEFAULT_LANGUAGE;
		this.t = function(key){
			if(!H5.Strings[lang]){
				return "UNDEFINED LANG: " + lang;
			} else if(!H5.Strings[lang][key]){
				return "UNTRANSLATED KEY ("+lang+"): " + key;
			} else {
				return H5.Strings[lang][key];
			}
		};
		this.setLocale = function(language){
			var lng = "";
			
			if(language){
				lng = language;
			} else {
				lng = this.DEFAULT_LANGUAGE;
			}
			
			if(H5.Strings[lng]){
				lang = lng;
			} else {
				var lngArr = lng.split("_");
				lng = lngArr[0].toLowerCase();
				if(H5.Strings[lng]){
					lang = lng;
				} else {
					lang = this.DEFAULT_LANGUAGE;
				}
			}
		};
		this.getLocale = function(){
			return lang;
		};
	};
	
	this.Storage = new function(){
		var isAvailable = function(){
			return (localStorage)? true : false;
		};
		this.isAvailable = function(){
			return isAvailable();
		};
		this.get = function(id){
			if(isAvailable){
				return localStorage.getItem(id);
			} else {
				return null;
			}
		};
		this.set = function(id, value){
			if(isAvailable){
				localStorage.setItem(id, value);
				return true;
			} else {
				return false;
			}
		};
		this.remove = function(id){
			if(isAvailable){
				localStorage.removeItem(id);
			}
		};
		this.clear = function(){
			if(isAvailable){
				localStorage.clear();
			}
		};
		this.length = function(){
			if(isAvailable){
				return localStorage.length;
			} else {
				return 0;
			}
		};
		this.key = function(id){
			if(isAvailable){
				return localStorage.key(id);
			} else {
				return null;
			}
		};
	};
	
	this.Database = new function(){
		this.init = function(name, size){
			if(openDatabase){
				H5.db = openDatabase(((name)? name : 'H5'), '1.0', 'H5 Database', ((size)? size : (5 * 1024 * 1024)));
				return true;
			} else {
				return false;
			}
		};
	};
	
	this.Log = new function(){
		this.debug = function(message){
			if(console && console.debug){
				console.debug(message, arguments);
			}
		};
		
		this.info = function(message){
			if(console && console.info){
				console.info(message, arguments);
			}
		};
		
		this.warn = function(message){
			if(console && console.warn){
				console.warn(message, arguments);
			}
		};
		
		this.error = function(message){
			if(console && console.error){
				console.error(message, arguments);
			}
		};
		
		this.clear = function(){
			if(console && console.clear){
				console.clear();
			}
		};
		
		this.assert = function(expression){
			if(console && console.assert){
				console.assert(expression, arguments);
			}
		};
		
		this.dir = function(object){
			if(console && console.dir){
				console.dir(object);
			}
		};
	};
	
	this.Loading = new function(){
		var overlay = null;
		var tplObject = {
			message: "",
		};
		var dialogCount = 0;
		var initDefaultOverlay = function(){
			$("#h5-loading-overlay-foreground").setTemplate(
			"<p><i class=\"icon-spinner icon-spin icon-2x\"></i> {$T.message}</p>" +
			"{$T.onload}", null, {runnable_functions: true}
			);
		};
		var initOverlay = function(){
			$("#h5-loading-overlay-foreground").setTemplateURL(overlay, null, {runnable_functions: true});
		};
		this.setOverlay = function(url){
			overlay = url;
		};
		this.setTemplateObject = function(object){
			tplObject = object;
		};
		this.show = function(dialogID){
			dialogCount++;
			if(overlay){
				initOverlay();
			} else {
				initDefaultOverlay();
				tplObject.onload = function(){
					window.setTimeout(function(){
						$("#h5-loading-overlay-foreground").css("margin-top", ($("#h5-loading-overlay").innerHeight() - $("#h5-loading-overlay-foreground").outerHeight())/2 + "px");
					}, 1);
				};
			}
			$("#h5-loading-overlay-foreground").processTemplate(tplObject);
			$("#h5-loading-overlay").show();
			H5.Log.debug("Showing LoadingDialog for " + dialogID);
		};
		this.hide = function(dialogID){
			dialogCount--;
			if(dialogCount <= 0) $("#h5-loading-overlay").hide();
			if(dialogCount < 0) dialogCount = 0;
			H5.Log.debug("Hiding LoadingDialog for " + dialogID);
		};
	};
	
	this.Dialog = new function(){
		var overlay = null;
		var tplObject = {
			message: "",
		};
		var initDefaultOverlay = function(){
			$("#h5-dialog-overlay-foreground").setTemplate(
			"<p><i class=\"icon-spinner icon-spin icon-2x\"></i> {$T.message}</p>" +
			"{$T.onload}", null, {runnable_functions: true}
			);
		};
		var initOverlay = function(){
			$("#h5-dialog-overlay-foreground").setTemplateURL(overlay, null, {runnable_functions: true});
		};
		this.setOverlay = function(url){
			overlay = url;
		};
		this.setTemplateObject = function(object){
			tplObject = object;
		};
		this.show = function(){
			if(overlay){
				initOverlay();
			} else {
				initDefaultOverlay();
				tplObject.onload = function(){
					window.setTimeout(function(){
						$("#h5-dialog-overlay-foreground").css("margin-top", ($("#h5-dialog-overlay").innerHeight() - $("#h5-dialog-overlay-foreground").outerHeight())/2 + "px");
					}, 1);
				};
			}
			$("#h5-dialog-overlay-foreground").processTemplate(tplObject);
			$("#h5-dialog-overlay").show();
		};
		this.hide = function(){
			$("#h5-dialog-overlay").hide();
		};
	};
	
	
};